﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Diagnostics;

namespace TaskUnitProject
{
    public class TaskUnit_2_2
    {
        private static List<Custom> customs = new List<Custom>();
        public static void Go()
        {
            //AddCustoms();
            ListWithParallel();
            //TestPLinq();
        }

        private static void AddCustoms()
        {
            for (int i = 0; i < 200000; i++)
            {
                customs.Add(new Custom() { Name = "Jack", Age = 21, Address = "NewYork" });
                customs.Add(new Custom() { Name = "Jime", Age = 26, Address = "China" });
                customs.Add(new Custom() { Name = "Tina", Age = 29, Address = "ShangHai" });
                customs.Add(new Custom() { Name = "Luo", Age = 30, Address = "Beijing" });
                customs.Add(new Custom() { Name = "Wang", Age = 60, Address = "Guangdong" });
                customs.Add(new Custom() { Name = "Feng", Age = 25, Address = "YunNan" });
            }
        }

        /// <summary>
        /// 线程安全集合
        /// </summary>
        private static void ListWithParallel()
        {
            Stopwatch stopwatch=new Stopwatch();
            //非线程安全集合
            List<int> list=new List<int>();
            stopwatch.Start();
            Parallel.For(0, 10000, item => { list.Add(item); });
            stopwatch.Stop();
            Console.WriteLine($"ListCount：{list.Count},耗时：{stopwatch.ElapsedMilliseconds} ms.");
            //线程安全集合（无序）
            ConcurrentBag<int> list2=new ConcurrentBag<int>();
            stopwatch.Restart();
            Parallel.For(0, 10000, item => { list2.Add(item); });
            
            stopwatch.Stop();
            Console.WriteLine($"ListCount：{list2.Count},耗时：{stopwatch.ElapsedMilliseconds} ms.");
        }

        /// <summary>
        /// 并行linq查询
        /// </summary>
        private static void TestPLinq()
        {
            Stopwatch sw=new Stopwatch();
            sw.Start();
            var result = customs.Where(c => c.Age > 26).ToList();
            sw.Stop();
            Console.WriteLine($"Linq runtim is {sw.ElapsedMilliseconds} ms.");
            sw.Restart();
            var result2 = customs.AsParallel().Where(c => c.Age > 26).ToList();
            sw.Stop();
            Console.WriteLine($"Parallel Linq runtim is {sw.ElapsedMilliseconds} ms");
            
        }

        private class Custom
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string Address { get; set; }
        }
    }
}
